import os

from PySide2.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QSizePolicy, QSpacerItem, QFileDialog, \
    QMessageBox, QPushButton

import pandas as pd
from .pd import save_df_to_excel
from .qttable import DFTable


class TablePage(QWidget):
    def __init__(self, view_name, table_widget: DFTable, db_name):
        super().__init__()
        self.view_name = view_name
        self.file_path = os.getcwd()
        self.db_name = db_name

        # 工具栏的结构
        self.header_tools = QWidget()
        self.qtable = table_widget
        self.left_tool = QWidget()
        self.mid_tool = QWidget()
        self.right_tool = QWidget()
        self.layout_header = QHBoxLayout(self.header_tools)
        # 显示信息的label
        self.message_label = QLabel(text="尚未授权访AED")
        self.message_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        self.message_label.setAutoFillBackground(False)
        self.message_label.setWordWrap(True)

        # 设置整体布局
        self.layout_main = QVBoxLayout(self)
        self.layout_main.addWidget(self.header_tools)
        self.layout_main.addWidget(self.message_label)
        self.layout_main.addWidget(self.qtable)

        # 工具栏相关属性

        # 默认功能
        self.btn_save_to_excel = QPushButton("导出Excel")
        self.btn_save_to_excel.clicked.connect(self.save_to_excel)
        self.btn_save_change_to_db = QPushButton("保存修改")
        self.header_left_spacer = QSpacerItem(100, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.header_right_spacer = QSpacerItem(50, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.left_tool_list = []
        self.mid_tool_list = []
        self.end_tool_list = []

    def init_tool_bar(self):
        layout_tool = self.layout_header
        if self.left_tool_list:
            for wgt in self.left_tool_list:
                layout_tool.addWidget(wgt)
        layout_tool.addItem(self.header_left_spacer)
        if self.mid_tool_list:
            for wgt in self.mid_tool_list:
                layout_tool.addWidget(wgt)
                layout_tool.addItem(self.header_right_spacer)
        if self.end_tool_list:
            for wgt in self.end_tool_list:
                layout_tool.addWidget(wgt)
        layout_tool.addWidget(self.btn_save_change_to_db)
        layout_tool.addWidget(self.btn_save_to_excel)

    def add_tool(self, widget_list: list, location=0):
        """
        向工具栏添加工具控件
        location: 0： 左侧  1： 中间    2： 右侧
        """
        if location == 0:
            tool_list = self.left_tool_list
        elif location == 1:
            tool_list = self.mid_tool_list
        else:
            tool_list = self.end_tool_list

        for wgt in widget_list:
            tool_list.append(wgt)

    def export_to_excel(self, df_data: pd.DataFrame):
        # 打开保存文件对话框
        filename, _ = QFileDialog.getSaveFileName(self, f'{self.view_name}.xlsx', self.file_path,
                                                  'Excel Files (*.xlsx)')
        if filename:
            # 如果用户选择了文件路径，将DataFrame保存为Excel文件
            save_df_to_excel(df_data, filename, self.view_name)
            QMessageBox.information(self, 'Success', '文件已保存成功.')

    def save_to_excel(self):
        """将查询的表格信息保存至Excel"""
        df_data: pd.DataFrame = self.qtable.datas_show
        if df_data.empty:
            QMessageBox.information(self, '数据为空', '没有数据要存储.')
            return
        else:
            self.export_to_excel(df_data)
